<template>
    <div>
        <div class="page-path-box">
            <el-cascader
                :options="options"
                :change-on-select="false"
                @change="handleChangeEvent"
                v-model="defaultChooseComputed"
                @active-item-change="handleItemChangeEvent"
                >
            </el-cascader>
            <!-- <s-code></s-code> -->
            <span v-show="goodsCodeInputIsShow" class="goods-code" @click="showSuspendMenu" id="goods-code">{{goodsCode}}</span>
        </div>
        <suspend-menu ref="mMenu" correlationId="#goods-code" :rootSelector="rootSelector">
            <s-code @getgoodscodedata="handleClickEvent"></s-code>
        </suspend-menu>
    </div>
</template>
<script>
    import {getActivityName, getActivityList} from "./axios"
    import {Cascader} from "element-ui";
    import router from "../../edit-router";
    import {mapGetters} from "vuex";
    import SearchProduct from "../SearchProduct";
    import "./index.css";
    import SuspendMenu from "../SuspendMenu";
    import mergeRouter from "../../utils/settings/mergeRouter";
    import { DatePicker } from "element-ui";
    import {LOCAL_OTHER_ROUTER} from "../../config/stystem-params";
    export default {
        props: {
            //当输入框里的值发生变化时的回调函数
            changeEvent: {
                type: Function,
                default: () => {}
            },
            //根元素的选择器，默认为浏览器视窗
            rootSelector: {
                type: String,
                default: ""
            },
            //回显的选中的路径值
            defaultChooseProps: {
                type: Array,
                default: () => []
            },
            //回显的商品编码
            defaultGoodsCodeProps: {
                type: String,
                default: ""
            },
        },
        data() {
            return {
                options: [],
                goodsCode: "请选择商品编码",
                goodsCodeInputIsShowState: false,//是否显示选择商品编码
                defaultChoose: [],
                //保存从后台请回来的活动名称列表
                activityNameList: {},
                activityCache: {}
            }
        },
        computed: {
            ...mapGetters("cjy", [
                /*"classifyData"*/
                "newClassifyData"
            ]),
            getRouterKey() {
            	//return 'EditRouter'
                return "ProductionRouter";
            },
            getClassifyData() {
                return this.newClassifyData;
            },
            //获取和设置默认的路径值
            defaultChooseComputed: {
                set(arr) {
                    this.defaultChoose = arr;
                },
                get() {
                    return this.defaultChoose;
                }
            },
            //获取和设置默认的商品编码
            defaultGoodsCodeComputed: {               
                set(goodsCode) {
                    this.goodsCode = goodsCode;
                },
                get() {
                    return this.goodsCode;
                }
            },
            //当goodsCodeInputIsShowState为true或者goodsCode有值的时候显示出商品选择框来
            goodsCodeInputIsShow() {
                return this.goodsCodeInputIsShowState || this.goodsCode !== "请选择商品编码";
            } 
        },
        methods: {
            FirstCapital(str) {
                return str.slice(0, 1).toUpperCase();
            },
            //定义正则表达式对象，判断是否是自定义页面
            regObject() {
                return {
                    isCust(value) {
                        let reg = /^cust.*$/;
                        return reg.test(value);
                    }
                }
            },
            //初始化菜单
            async initOptions() {
                let opt = [
                    {
                        label: "分类页面",
                        value: "分类页面",
                        id: "classify",
                        children: []
                    },
                    {
                        label: "商品详情页面",
                        value: "商品详情页面",
                        id: "detail",
                    },
                    {
                        label: "其他页面",
                        value: "其他页面",
                        id: "other",
                        children: []
                    },
                ];
                //填充分类的配置页面
                Array.isArray(this.getClassifyData) && this.getClassifyData.forEach((parentItem, index) => {
                    /*let parent = {
                        label: parentItem.goodsclassname,
                        value: parentItem.goodsclasscode + "-" + parentItem.goodsclassname,
                        id: parentItem.goodsclasscode,
                    }*/
                   let parent = {
                        label: parentItem.className,
                        value: parentItem.classCode + "-" + parentItem.className,
                        id: parentItem.classCode,
                    }
                    //配置二级分类
                    //清除第一个分类，第一个分类为全部(即为本身)
                    // parentItem.secList.shift();
                    parentItem.secList.forEach(childItem => {
                        if (!parent.children) {
                            parent.children = [];
                        }
                        let child = {
                            label: childItem.goodsClassName,
                            value: childItem.goodsClassCode + "-" + childItem.goodsClassName,
                            id: childItem.goodsClassName,
                        }
                        parent.children.push(child);
                    });
                    this.getMenuItemById("classify", opt).children.push(parent);
                });
                let otherRouter = mergeRouter();
                //填充其他页面
                otherRouter.filter(item => {
                    return item.state !== 0;
                }).forEach((item, index) => {
                    let obj = {
                        label: item.title ? item.title : item.name,
                        value: item.name + "-" + (item.title ? item.title : item.name)
                    }
                    this.getMenuItemById("other", opt).children.push(obj);
                });
                //添加进去本地的路由结构
                let localArr = LOCAL_OTHER_ROUTER;
                this.getMenuItemById("other", opt).children.push(...localArr);
                this.options = opt;
            },
            //根据id获取options对应的菜单项
            getMenuItemById(id, opt = this.options) {
                //校验id值
                if (!id) {
                    console.log(console.warn("请传入id值"));
                    return;
                }
                for (let item of opt) {
                    if (item.id === id) {
                        return item;
                    }
                }
                
            },
            initInputState() {
                this.goodsCodeInputIsShowState = false;
                this.goodsCode = "请选择商品编码";
            },
            //当路径选择框发生变化时的回调方法
            handleChangeEvent(arr) {
                //默认隐藏商品详情输入框
                this.initInputState();
                // console.log("当路径选择框发生变化时的回调方法", arr);
                let group = arr[0];
                let UIContent = "";
                arr.forEach(item => {
                    //截取后一个值 
                    UIContent += "/" + (item.indexOf("-") > -1 ? item.split("-")[1] : item);
                });
                //分类、自定义、商品详情、其他
                let obj = {
                    UIContent: UIContent.slice(1),
                    valueArray: arr,
                    path: "",
                }
                // console.log("UIContent", obj.UIContent);
                // console.log("UIContent", obj.valueArray);
                let path;
                switch (group) {
                    case "分类页面":
                        //对于分类页面来说，arr[0]是分类组名，arr[1].split("-")[0]是一级分类编码，arr[2].split("-")[0]是2级分类编码
                        arr[1] && (obj.path = `goodsClassify?classCode=${arr[2] ? arr[2].split("-")[0] : arr[1].split("-")[0]}`);
                        arr[1] && this.changeEvent(obj);
                        this.goodsCodeInputIsShowState = false;
                        break;
                    case "商品详情页面":
                        //显示商品详情输入框
                        this.goodsCodeInputIsShowState = true;
                        break;
                    case "自定义页面":
                        arr[1] && (obj.path = `${arr[2] ? arr[2].split("-")[0] : arr[1].split("-")[0]}`);
                        arr[1] && this.changeEvent(obj);
                         this.goodsCodeInputIsShowState = false;
                        break;
                    case "其他页面":
                        arr[1] && (obj.path = `${arr[2] ? arr[2].split("-")[0] : arr[1].split("-")[0]}`);
                        arr[1] && this.changeEvent(obj);
                        this.goodsCodeInputIsShowState = false;
                        break;
                    default:
                        break;
                }
                
            },
            //显示悬浮菜单
            showSuspendMenu() {
                this.$refs.mMenu.showMenu();
            },
            //处理商品编码的选择事件
            handleClickEvent(goodsCode) {
                this.goodsCode = goodsCode;
                this.$refs.mMenu.hideMenu();
            },
            //校验请求参数是否合法
            validatorFn(data) {
                if (data.status === 200 && data.data.data[0]) {
                    return true;
                } else {
                    return false;
                }
            },
            //获取活动名称
            async getActivityNameFn() {
                //如果有数据则无需请求数据
                if (this.activityNameList.length) {
                    return;
                }
                let data = await getActivityName();
                this.validatorFn(data) && (this.activityNameList = data.data.data[0].saleTypes);
                // console.log("getActivityNameFn", data);
            },
            async handleItemChangeEvent(arr) {
                console.log(arr);
                //当进入营销活动的时候才执行后续方法
                if (arr[0] === "营销活动页面") {
                    // console.log("dsddssdsdsds");
                    //如果没有缓存
                    if (arr[1] && !this.activityCache[arr[1]]) {
                        let data = await getActivityList(arr[1]);
                        console.log("活动列表", data);
                        if (this.validatorFn(data)) {
                            //数据格式正确
                            //把数据存到缓存
                            this.activityCache[arr[1]] = data.data.data[0];
                            //从缓存中读取数据
                            this.loadActivityData(arr[1], this.activityCache[arr[1]]);
                        } else {
                            console.warn(`获取${arr[1]}数据失败`);
                        }
                    } else if (arr[1] && this.activityCache[arr[1]]){
                        //读缓存
                        this.loadActivityData(arr[1], this.activityCache[arr[1]]);
                    }
                }
                // console.log(val);
            },
            //将营销活动的第三级数据数据压到第三级菜单
            loadActivityData(value, obj) {
                let menuItem = this.getMenuItemById("activity");
                console.log("menuItem=", menuItem);
                let itemOfMenuItem;
                for (let item of menuItem.children) {
                    if (item.value === value) {
                        itemOfMenuItem = item;
                        break;
                    }
                }
                console.log("itemOfMenuItem=", itemOfMenuItem);
                if (!itemOfMenuItem.children.length) {
                    console.log(value + "没有值，需要重新赋值");
                    console.log(obj);
                    for (let key in obj) {
                        itemOfMenuItem.children.push({
                            label: obj[key],
                            value: key
                        });
                    }
                }
                
            }
        },
        components: {
            "el-cascader": Cascader,
            "s-code": SearchProduct,
            "suspend-menu": SuspendMenu,
            "el-date-picker": DatePicker,
        },
        created() {
            this.initOptions();
            this.getActivityNameFn();
            // console.log("这里是pagepath组件");
        },
        watch: {
            goodsCode(newVal, oldVal) {
                // console.log("goodsCode newVal", newVal);
                if (newVal.indexOf("请选择") === -1) {
                    let obj = {
                        valueArray: ["商品详情页面"],
                        UIContent: "商品详情页面",
                        path: `detail?code=${newVal}`,
                    }
                    // let ß = 2;
                    // console.log(ß);
                    // let path = `detail?code=${newVal}`;
                    this.changeEvent(obj);
                }
            },
            //监听回显的路径选择数组
            defaultChooseProps(arr) {
                this.defaultChooseComputed = arr;
            },
            //监听回显的商品编码
            defaultGoodsCodeProps(goodsCode) {
                this.defaultGoodsCodeComputed = goodsCode;
            }
        }
    }
</script>
<style scoped>
.page-path-box {
    display: flex;
    
}
.goods-code {
    width: 150px;
    margin-left: 20px;
    cursor: pointer;
}
</style>

